<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-5-12
 * Time: 下午10:03
 */

namespace Library\route;


use Application\Base\mdlBase;
use Application\Base\mdlError;

class LibBase extends \LibBase
{

    /**
     * 项目名称
     * @var string
     */
    protected $application = "";

    /**
     * 模块方法
     * @var string
     */
    protected $module = "";

    /**
     * 模块方法
     * @var string
     */
    protected $method = "";

    /**
     * 请求URl
     * @var string
     */
    protected $url = "";

    public function init($request)
    {
        $request = explode("?", $request);
        $this->url = $request[0];
        if ($this->url) {
            $this->action();
        } else {
            $this->application = DEFAULT_APPLICATION;
            $this->module = DEFAULT_MODULE;
            $this->method = DEFAULT_METHOD;
        }
        $this->run();
    }

    /**
     * 处理route参数的方式
     */
    public function action()
    {

    }

    /**
     * 过滤参数的方法
     * @param $params
     * @param $uc
     * @param bool $default 是否需要填充参数默认值
     * @return mixed|string
     */
    public function filter($params, $uc = false, $default = TRUE)
    {
        $params = preg_replace('/^\W$/', "", trim($params));
        if (!$params && $default) {
            $params = "index";
        }
        $uc && $params = ucfirst($params);
        return $params;
    }

    /**
     * 运行控制层类
     */
    public function run()
    {
        $method = "func" . $this->method;
        $clsName = "ctl" . $this->module;
        $ctlFile = SYS_APPLICATION . $this->application . DIRECTORY_SEPARATOR . "source" . DIRECTORY_SEPARATOR . $clsName . ".php";
        if (!file_exists($ctlFile)) {
            \LibLog::custom("Module '{$this->module}' not exists");
            exit();
        }
        include_once($ctlFile);
        $clsName = sprintf("\%s\%s\%s", "Application", $this->application, $clsName);
        /**
         * @var \Application\Base\ctlBase $ctlObj
         */
        $ctlObj = new $clsName();
        if (!method_exists($ctlObj, $method)) { //为了让不存在的方法都跳转到正确的地址
            $method = "funcIndex";
            $this->method = 'index';
        }
        $ctlObj->init($this->application, $this->module, $this->method, $this->url);
        try {
            $ctlObj->$method();
        } catch (\Exception $e) {
            mdlError::response();
        }
        return true;
    }
}